package cn.wolfcode.p2p.website.controller;

import java.math.BigDecimal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.base.domain.UserInfo;
import cn.wolfcode.p2p.base.exception.DisplayableException;
import cn.wolfcode.p2p.base.service.IAccountService;
import cn.wolfcode.p2p.base.service.IRealAuthService;
import cn.wolfcode.p2p.base.service.IUserInfoService;
import cn.wolfcode.p2p.base.util.Constants;
import cn.wolfcode.p2p.base.util.JSONResult;
import cn.wolfcode.p2p.base.util.UserContext;
import cn.wolfcode.p2p.business.domain.BidRequest;
import cn.wolfcode.p2p.business.query.PaymentScheduleQueryObject;
import cn.wolfcode.p2p.business.service.IBidRequestService;

/**
 * 前台借款相关的控制器
 * 
 * @author wolfcode
 *
 */
@Controller
public class BorrowController {

	@Autowired
	private IAccountService accountService;

	@Autowired
	private IUserInfoService userinfoService;

	@Autowired
	private IBidRequestService bidRequestService;

	@Autowired
	private IRealAuthService realAuthService;

	/**
	 * 借款详细页面
	 */
	@RequestMapping("borrow_info")
	public String borrowDetailPage(Long id, Model model) {
		BidRequest br = this.bidRequestService.get(id);
		if (br != null && br.getBidRequestState() != Constants.BIDREQUEST_STATE_APPLY) {
			model.addAttribute("bidRequest", br);
			UserInfo borrowUser = this.userinfoService.get(br.getCreateUser().getId());
			model.addAttribute("userInfo", borrowUser);

			LoginInfo current = UserContext.getCurrent();
			if (current != null) {
				// 如果用户是借款人
				if (current.getId().equals(borrowUser.getId())) {
					model.addAttribute("self", true);
				} else {
					// 如果当前用户是投资人
					model.addAttribute("account", this.accountService.get(current.getId()));
				}
			}

			// 借款人实名认证信息
			model.addAttribute("realAuth", this.realAuthService.get(borrowUser.getRealAuthId()));
		}
		return "borrow_info";
	}

	/**
	 * 借款首页
	 */
	@RequestMapping("borrow")
	public String borrowIndex(Model model) {
		// 如果当前用户没有登录,直接跳转到静态的借款首页
		LoginInfo current = UserContext.getCurrent();
		if (current == null) {
			return "redirect:/borrowIndex.html";
		} else {
			// 否则,添加模板内容,导向到borrow.ftl
			// 当前用户的账户信息
			model.addAttribute("account", this.accountService.get(current.getId()));
			// 当前usreinfo
			model.addAttribute("userInfo", this.userinfoService.get(current.getId()));
			return "borrow";
		}
	}

	/**
	 * 导向到借款申请页面
	 */
	@RequestMapping("borrowInfo")
	public String borrowApplyPage(Model model) {
		UserInfo current = this.userinfoService.get(UserContext.getCurrent().getId());
		if (current.getHasBasicInfo() && current.getHasRealAuth() && current.getHasVideoAuth()) {
			if (current.getHasBidRequestInProcess()) {
				// 如果用户有一个借款在审核流程当中,页面导向到borrow_apply_result
				return "borrow_apply_result";
			} else {
				// 导向到borrow_apply
				// 最小借款金额
				model.addAttribute("minBidRequestAmount", Constants.BORROW_AMOUNT_MIN);
				model.addAttribute("account", this.accountService.get(current.getId()));
				// 系统规定最小投标金额
				model.addAttribute("minBidAmount", Constants.BID_AMOUNT_MIN);
				return "borrow_apply";
			}
		} else {
			return "redirect:/borrow";
		}
	}

	/**
	 * 提交借款申请
	 */
	@RequestMapping("borrow_apply")
	@ResponseBody
	public JSONResult borrowApply(BidRequest to) {
		JSONResult result = new JSONResult();
		try {
			this.bidRequestService.apply(to);
		} catch (DisplayableException ex) {
			result = new JSONResult(false, ex.getMessage());
		} catch (Exception e) {
			// 把错误信息记录到服务器中日志文件中,方便排查问题.
			result = new JSONResult(false, "系统异常,请联系管理员!");
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 投标
	 */
	@RequestMapping("borrow_bid")
	@ResponseBody
	public JSONResult bid(Long bidRequestId, BigDecimal amount) {
		JSONResult result = new JSONResult();
		try {
			this.bidRequestService.bid(bidRequestId, amount);
		} catch (DisplayableException ex) {
			result = new JSONResult(false, ex.getMessage());
		} catch (Exception e) {
			// 把错误信息记录到服务器中日志文件中,方便排查问题.
			result = new JSONResult(false, "系统异常,请联系管理员!");
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 列出还款列表
	 */
	@RequestMapping("borrowBidReturn_list")
	public String returnList(@ModelAttribute("qo") PaymentScheduleQueryObject qo, Model model) {
		qo.setUserId(UserContext.getCurrent().getId());
		model.addAttribute("pageResult", this.bidRequestService.queryPaymentSchedules(qo));
		model.addAttribute("account", this.accountService.get(UserContext.getCurrent().getId()));
		return "returnmoney_list";
	}
	
	/**
	 * 执行还款
	 */
	@RequestMapping("returnMoney")
	@ResponseBody
	public JSONResult returnMoney(Long id){
		JSONResult result = new JSONResult();
		try {
			this.bidRequestService.returnMoney(id);
		} catch (DisplayableException ex) {
			result = new JSONResult(false, ex.getMessage());
		} catch (Exception e) {
			// 把错误信息记录到服务器中日志文件中,方便排查问题.
			result = new JSONResult(false, "系统异常,请联系管理员!");
			e.printStackTrace();
		}
		return result;
	}

}
